package com.jfinal.code.eclipse.plugin.generator.strategy;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.util.Map;

import com.jfinal.code.eclipse.plugin.generator.db.DbUtils;
import com.jfinal.code.eclipse.plugin.generator.dto.ValueDTO;
import com.jfinal.code.eclipse.plugin.i18n.I18n;
import com.yaolin.generator.api.Generator;
import com.yaolin.generator.api.Table;
/**
 * 自定义生成策略代码生成
 * <p>我伏案写宣纸悲，杯盏难懂茶色的韵味。</p>
 * @author yaolin
 *
 */
public class CustomGenerateStrategy implements GenerateStrategy {

	@SuppressWarnings({"rawtypes"})
	@Override
	public void generateCode(String[] tableNames, String[] selectedTableNames, ValueDTO valueDTO) {
		if (valueDTO == null || valueDTO.getDatabaseInfoValueDTO() == null || valueDTO.getCustomValueDTO() == null) {
			return;
		}
		if (selectedTableNames == null || selectedTableNames.length == 0) {
			return ;
		}
		// 获取数据库表缓存数据，如果没有，则重新缓存一次再获取
		Map<String, Table> listTable = DbUtils.DbInfoHolder.getCache();
		if (listTable.isEmpty()) {
			try {
				Connection conn = DbUtils.getConnection(valueDTO.getDatabaseInfoValueDTO().getJarFile(), valueDTO.getDatabaseInfoValueDTO().getDriverClassName(),
						valueDTO.getDatabaseInfoValueDTO().getUrl(),
						valueDTO.getDatabaseInfoValueDTO().getUsername(), valueDTO.getDatabaseInfoValueDTO().getPassword());
				//  cache table;
				DbUtils.listTable(valueDTO.getDatabaseInfoValueDTO().getDbType(), conn);
				DbUtils.closeConnection(conn);
				listTable = DbUtils.DbInfoHolder.getCache();
			} catch (Throwable e) {
				throw new RuntimeException(e);
			}
		}
		
		try {
			// 加载自定义拓展生成策略jar包
			File file = new File(valueDTO.getCustomValueDTO().getCustomJar());
			URLClassLoader loader = new URLClassLoader(new URL[] { file.toURI().toURL() },
					Thread.currentThread().getContextClassLoader());
			Class clazz = loader.loadClass(valueDTO.getCustomValueDTO().getCustomImplClassName());
			Generator generator = (Generator) clazz.newInstance();
			// 调用Generator接口生成代码
			for (String tableName : selectedTableNames) {
				generator.generate(valueDTO.getCustomValueDTO().getTemplatePath(),
					valueDTO.getCustomValueDTO().getBasePackageName(),
					valueDTO.getCustomValueDTO().getJavaPath(),
					valueDTO.getCustomValueDTO().getResourcePath(),
					valueDTO.getCustomValueDTO().getJsPath(),
					valueDTO.getCustomValueDTO().getViewPath(),
					listTable.get(tableName)
				);
			}
		} catch (InstantiationException e) {
			throw new RuntimeException(I18n.error_generator_instantiation, e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(I18n.error_generator_instantiation, e);
		} catch (Exception e) {
			throw new RuntimeException(I18n.error_generator_notfound, e);
		}
	}

}
